package com.common;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.model.SysUser;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class TokenUtils {

    private Log log = LogFactory.getLog(this.getClass());

    public static String secret = "uwo!#$ijdsnaf!#$19321092ksdfsanf!@!#$#@$";

    public String generateToken(SysUser su) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", su.getId());
        claims.put("username", su.getUsername());
        claims.put("name", su.getName());

        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000 * 1; // 1小时有效时间
        return Jwts.builder().setClaims(claims).setExpiration(new Date(currentTime))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    public SysUser decodeToken(String authToken) {
        try {
            final Claims claims = getClaimsFromToken(authToken);
            SysUser su = new SysUser();
            su.setId(Long.valueOf(String.valueOf(claims.get("id"))));
            su.setUsername((String) claims.get("username"));
            su.setName((String) claims.get("name"));
            return su;
        } catch (Exception e) {
            log.error("token解析失败!", e);
            return null;
        }
    }

    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }
}
